package com.foreverwin.mes.lims.controller;

import com.alibaba.fastjson.JSONObject;
import com.foreverwin.mes.core.base.FrontPage;
import com.foreverwin.mes.core.base.AjaxResult;
import com.foreverwin.mes.core.utils.CommonMethods;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.foreverwin.mes.lims.service.ItemTankService;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.foreverwin.mes.lims.service.LotTankService;
import com.foreverwin.mes.lims.model.LotTank;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;

/**
 *
 * @author Max
 * @since 2020-03-13
 */
@Controller
@RequestMapping("/lotTanks")
public class LotTankController {
    private final Logger logger = LoggerFactory.getLogger(LotTankController.class);

    @Autowired
    private LotTankService lotTankService;
    @Autowired
    private ItemTankService itemTankService;

    /**
    * 根据id查询
    *
    * @param id 主键
    * @return
    */
    @ResponseBody
    @GetMapping("/{id:.+}")
    public AjaxResult getLotTankById(@PathVariable String id) {
        LotTank result;
        try {
            result = lotTankService.selectById(id);
        } catch (Exception e) {
            logger.error("getLotTankById -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 查询所有数据
     *
     * @return
     */
    @ResponseBody
    @GetMapping("")
    public AjaxResult getLotTankList(LotTank lotTank){
        List<LotTank> result;
        try {
           /* EntityWrapper<LotTank> EntityWrapper = new EntityWrapper<>();
            String zItemTankBo = lotTank.getHandle();
            LotTank _lotTank = new LotTank();
            _lotTank.setzItemTankBo( zItemTankBo );
            EntityWrapper.setEntity(_lotTank);
            result = lotTankService.selectList(EntityWrapper);*/
            String zItemTankBo = lotTank.getHandle();
            result = lotTankService.selectLotOfTankList(zItemTankBo);
        } catch (Exception e) {
            logger.error("getLotTankList -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 分页查询数据
     *
     * @param frontPage  分页信息
     * @return
     */
    @ResponseBody
    @GetMapping("/getLotTankPageList")
    public AjaxResult getLotTankPageList(FrontPage<LotTank> frontPage, LotTank lotTank){
        Page result;
        try {
            String site = CommonMethods.getSite();
            lotTank.setSite(site);
            EntityWrapper<LotTank> EntityWrapper = new EntityWrapper<>();
            EntityWrapper.setEntity(lotTank);
            if (frontPage.getGlobalQuery() != null && !"".equals(frontPage.getGlobalQuery().trim())) {
                //TODO modify global query
                EntityWrapper
                    .like("handle", frontPage.getGlobalQuery())
                    .or().like("zItemTankBo", frontPage.getGlobalQuery())
                    .or().like("site", frontPage.getGlobalQuery())
                    .or().like("lot", frontPage.getGlobalQuery())
                    .or().like("resrce", frontPage.getGlobalQuery())
                    .or().like("resrceDesc", frontPage.getGlobalQuery())
                    .or().like("tankByUse", frontPage.getGlobalQuery())
                    .or().like("moveType", frontPage.getGlobalQuery())
                    .or().like("lotStatus", frontPage.getGlobalQuery())
        ;
            }
            result = lotTankService.selectPage(frontPage.getPagePlus(), EntityWrapper);
        } catch (Exception e) {
            logger.error("getLotTankPageList -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 保存和修改公用
     * @param lotTank  传递的实体
     * @return  null 失败  实体成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_save")
    public AjaxResult lotTankSave(@RequestBody LotTank lotTank) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        int count;
        try {
            count = lotTankService.insertOrUpdate(lotTank) ? 1 : 0;
        } catch (Exception e) {
            logger.error("lotTankSave -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(count == 0 ? null : lotTank);
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.DELETE, value = "/{id:.+}")
    public AjaxResult lotTankDelete(@PathVariable("id") String id){
        int count;
        try {
            count = lotTankService.deleteById(id) ? 1 : 0;
        } catch (Exception e) {
            logger.error("lotTankDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success("count: " + count);
    }

    /**
     * 批量删除对象
     * @param ids 实体集合ID
     * @return  0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_batchDelete")
    public AjaxResult removeByIds(List<String> ids){
        int count;
        try {
            count = lotTankService.deleteBatchIds(ids) ? 1 : 0;
        } catch (Exception e) {
            logger.error("lotTankBatchDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success("count: " + count);
    }

    /*@JmsListener(destination = "LOT_IN_OR_OUT_TANK")
    public void lotInOrOutTank( String text ) {
        logger.info( "<<<<<<=======消息队列[LOT_IN_OR_OUT_TANK]，接收到信息!");
        try {
            JSONObject obj = JSONObject.parseObject(text);
            String site = obj.getString("SITE");
            String tank = obj.getString( "TANK" );
            String lot = obj.getString( "LOT" );
            String qty = obj.getString( "QTY" );
            String item = obj.getString( "ITEM" );
            String moveType = obj.getString( "MOVE_TYPE" );
            Date actionTime = obj.getDate( "ACTION_TIME");
            lotTankService.lotCheckinOrCheckOut(site,tank,lot,qty,item,moveType,actionTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @JmsListener(destination = "TANK_HIGH_OR_LOW")
    public void tankHighOrLow( String text ) {
        logger.info( "<<<<<<=======消息队列[TANK_HIGH_OR_LOW]，接收到信息!");
        try {
            JSONObject obj = JSONObject.parseObject(text);
            String site = obj.getString("SITE");
            String tank = obj.getString( "TANK" );
            String item = obj.getString( "ITEM" );
            String highOrLow = obj.getString( "HIGH_OR_LOW" );
            Date actionTime = obj.getDate( "ACTION_TIME");
            itemTankService.tankHighOrLow( site,tank,item,highOrLow,actionTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/
}